using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace S.M.SmartMedical.Infrastructure
{
    /// <summary>
    /// EF Core迁移时的DbContext工厂类
    /// 用于在设计时创建DbContext实例
    /// </summary>
    public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
    {
        /// <summary>
        /// 创建DbContext实例用于迁移
        /// </summary>
        /// <param name="args">命令行参数</param>
        /// <returns>DbContext实例</returns>
        public MyDbContext CreateDbContext(string[] args)
        {
            // 从项目根目录读取配置文件
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true)
                .Build();

            // 获取连接字符串，使用默认值
            var connectionString = configuration.GetConnectionString("DefaultConnection") ??
                "Server=localhost;Port=3306;Database=Medical;User=root;Password=20050127";

            var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
            optionsBuilder.UseMySql(
                connectionString,
                new MySqlServerVersion("5.7"));

            return new MyDbContext(optionsBuilder.Options);
        }
    }
}